package com.yt.ds.chapter4;

import java.util.Stack;

/**
 * @Author: lzf
 * @Date: 2020/7/28 14:33
 * @Description: 深度优先搜索路径
 */
public class DepthFirstPaths implements Paths {
    private boolean[] marked;
    private int[] edgeTo;
    private final int s;        // 起点

    public DepthFirstPaths(Graph graph, int s) {
        marked = new boolean[graph.getVertexNum()];
        edgeTo = new int[graph.getVertexNum()];
        this.s = s;
        dfs(graph, s);
    }

    /**
     * 描述： 深度优先搜素，第一次访问点之后，就存储访问的前一个结点
     *
     * @param graph 图
     * @param v     目标结点
     * @return "void"
     * @date: 2020/7/28 14:43
     */
    private void dfs(Graph graph, int v) {
        marked[v] = true;
        for (int w : graph.adj(v)) {
            if (!marked[w]) {
                edgeTo[w] = v;
                dfs(graph, w);
            }
        }
    }

    @Override
    public boolean hasPathTo(int v) {
        return marked[v];
    }

    @Override
    public Iterable<Integer> pathTo(int v) {
        if (!hasPathTo(v)) {
            return null;
        }
        Stack<Integer> path = new Stack<>();
        for (int x = v; x != s; x = edgeTo[x]) {
            path.push(x);
        }
        path.push(s);
        return path;
    }
}
